package com.skit.spannablestringdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        SpannableString spannableString = new SpannableString("用户协议");
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                showToast();
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(getResources().getColor(R.color.colorAccent)); //设置颜色
            }
        }, 0, spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        textView.setText("点击登录表明同意");
        textView.append(spannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());//激活链接
    }

    private void showToast() {
        Toast.makeText(this, "协议被点击", Toast.LENGTH_SHORT).show();
    }
}
